package com.quick.develop.flowable.framework.convert.definition;

import com.quick.develop.flowable.domain.vo.group.BpmGroupUserVO;
import com.quick.develop.flowable.domain.vo.system.SysApiRole;
import com.quick.develop.framework.utils.collection.CollectionUtils;
import org.flowable.idm.api.Group;
import org.flowable.idm.api.User;
import org.flowable.idm.engine.impl.persistence.entity.GroupEntityImpl;
import org.mapstruct.Mapper;
import org.mapstruct.Mapping;
import org.mapstruct.MappingTarget;
import org.mapstruct.factory.Mappers;

import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 * @author junyuan.liu
 * @description: TODO
 * @date 2022/5/19 19:15
 */
@Mapper
public interface BpmGroupUserConvert {
    BpmGroupUserConvert INSTANCE = Mappers.getMapper(BpmGroupUserConvert.class);

    default List<BpmGroupUserVO> convertList(List<Group> list, Map<String, List<User>> userMap) {
        return CollectionUtils.convertList(list, group -> {
            BpmGroupUserVO groupUserVO = convert(group);
            groupUserVO.setUserList(convertList1(userMap.get(group.getId())));
            groupUserVO.setUserStr(buildUserStr(userMap.get(group.getId())));

            return groupUserVO;
        });

    }

    BpmGroupUserVO convert(Group group);

    default List<BpmGroupUserVO.GroupUser> convertList1(List<User> list) {
        return CollectionUtils.convertList(list, this::convert1);
    }

    BpmGroupUserVO.GroupUser convert1(User user);


    @Mapping(source = "from.id", target = "to.id", ignore = true)
    void copyTo(BpmGroupUserVO from, @MappingTarget Group to);

    default List<BpmGroupUserVO> convert1(List<Group> list) {
        return CollectionUtils.convertList(list, this::convert);
    }

    default String buildUserStr(List<User> list) {
        StringBuilder users = new StringBuilder();
        list.forEach(u -> {
            users.append(u.getId()).append("[")
                    .append(u.getDisplayName()).append("]；");
        });

        return users.substring(0, users.length() - 1);
    }

    default List<Group> convertList2(List<SysApiRole> list) {
        return CollectionUtils.convertList(list, sa -> {
            Group group = new GroupEntityImpl();
            Optional.ofNullable(sa.getRoleId()).ifPresent(group::setId);
            if (sa.getRoleId() != null) {
                group.setId(sa.getRoleId());
            }
            group.setName(sa.getRoleName());
            return group;
        });
    }

}
